<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="160px"
      v-loading="formLoading"
    >
      <el-form-item label="产品名称" prop="name">
        <el-input v-model="formData.name" placeholder="请输入产品名称" />
      </el-form-item>
      <el-form-item label="产品条码" prop="barCode">
        <el-input v-model="formData.barCode" placeholder="请输入产品条码" />
      </el-form-item>
      <el-form-item label="产品分类" prop="categoryId">
     <el-select v-model="formData.categoryId" clearable placeholder="请选择" class="!w-240px">
          <el-option
            v-for="item in productCategory"
            :key="item.value"
            :label="item.name"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="单位编号" prop="unitId">
        <el-select v-model="formData.unitId" clearable placeholder="请选择" class="!w-240px">
          <el-option
            v-for="item in unitOption"
           :key="item.value"
            :label="item.name"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="产品状态" prop="status">
         <el-select v-model="formData.status" clearable placeholder="请选择" class="!w-240px">
          <el-option
            v-for="item in statusOptions"
           :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="产品规格" prop="standard">
        <el-input v-model="formData.standard" placeholder="请输入产品规格" />
      </el-form-item>
      <el-form-item label="产品备注" prop="remark">
        <el-input v-model="formData.remark" placeholder="请输入产品备注" />
      </el-form-item>
      <el-form-item label="保质期天数" prop="expiryDay">
        <el-input v-model="formData.expiryDay" placeholder="请输入保质期天数" />
      </el-form-item>
      <el-form-item label="基础重量（kg）" prop="weight">
        <el-input v-model="formData.weight" placeholder="请输入基础重量（kg）" />
      </el-form-item>
      <el-form-item label="采购价格，单位：元" prop="purchasePrice">
        <el-input v-model="formData.purchasePrice" placeholder="请输入采购价格，单位：元" />
      </el-form-item>
      <el-form-item label="销售价格，单位：元" prop="salePrice">
        <el-input v-model="formData.salePrice" placeholder="请输入销售价格，单位：元" />
      </el-form-item>
      <el-form-item label="最低价格，单位：元" prop="minPrice">
        <el-input v-model="formData.minPrice" placeholder="请输入最低价格，单位：元" />
      </el-form-item>
      <el-form-item label="产品属性" prop="productAttribute">
        <el-input v-model="formData.productAttribute" placeholder="请输入产品属性" />
      </el-form-item>
      <el-form-item label="单位（基本单位）" prop="unit">
        <el-input v-model="formData.unit" placeholder="请输入单位（基本单位）" />
      </el-form-item>
      <el-form-item label="入库备注" prop="warehousingRemark">
        <el-input v-model="formData.warehousingRemark" placeholder="请输入入库备注" />
      </el-form-item>
      <el-form-item label="副单位" prop="secondaryUnit">
        <el-input v-model="formData.secondaryUnit" placeholder="请输入副单位" />
      </el-form-item>
      <el-form-item label="副单位数量" prop="secondaryUnitQuantity">
        <el-input v-model="formData.secondaryUnitQuantity" placeholder="请输入副单位数量" />
      </el-form-item>
      <el-form-item label="销售单价（辅助单位）" prop="salePriceSecondary">
        <el-input v-model="formData.salePriceSecondary" placeholder="请输入销售单价（辅助单位）" />
      </el-form-item>
      <el-form-item label="成本单价（辅助单位）" prop="costPriceSecondary">
        <el-input v-model="formData.costPriceSecondary" placeholder="请输入成本单价（辅助单位）" />
      </el-form-item>
      <el-form-item label="批号" prop="batchNumber">
        <el-input v-model="formData.batchNumber" placeholder="请输入批号" />
      </el-form-item>
      <el-form-item label="供应商名称" prop="supplierName">
        <el-input v-model="formData.supplierName" placeholder="请输入供应商名称" />
      </el-form-item>
      <el-form-item label="规格" prop="spec">
        <el-input v-model="formData.spec" placeholder="请输入规格" />
      </el-form-item>
      <el-form-item label="外箱尺寸" prop="outerBoxSize">
        <el-input v-model="formData.outerBoxSize" placeholder="请输入外箱尺寸" />
      </el-form-item>
      <el-form-item label="客户名称" prop="customerName">
        <el-input v-model="formData.customerName" placeholder="请输入客户名称" />
      </el-form-item>
      <el-form-item label="货号" prop="itemNo">
        <el-input v-model="formData.itemNo" placeholder="请输入货号" />
      </el-form-item>
      <el-form-item label="包装" prop="packageInfo">
        <el-input v-model="formData.packageInfo" placeholder="请输入包装" />
      </el-form-item>
      <el-form-item label="切割费用/米" prop="cuttingCostPerMeter">
        <el-input v-model="formData.cuttingCostPerMeter" placeholder="请输入切割费用/米" />
      </el-form-item>
      <el-form-item label="刺穿点费用/个" prop="piercingCostPerPiece">
        <el-input v-model="formData.piercingCostPerPiece" placeholder="请输入刺穿点费用/个" />
      </el-form-item>
      <el-form-item label="打点费用/个" prop="dottingCostPerPiece">
        <el-input v-model="formData.dottingCostPerPiece" placeholder="请输入打点费用/个" />
      </el-form-item>
      <el-form-item label="重量" prop="weightNew">
        <el-input v-model="formData.weightNew" placeholder="请输入重量" />
      </el-form-item>
      <el-form-item label="尺码" prop="size">
        <el-input v-model="formData.size" placeholder="请输入尺码" />
      </el-form-item>
      <el-form-item label="单重" prop="singleWeight">
        <el-input v-model="formData.singleWeight" placeholder="请输入单重" />
      </el-form-item>
      <el-form-item label="长" prop="length">
        <el-input v-model="formData.length" placeholder="请输入长" />
      </el-form-item>
      <el-form-item label="宽" prop="width">
        <el-input v-model="formData.width" placeholder="请输入宽" />
      </el-form-item>
      <el-form-item label="高" prop="height">
        <el-input v-model="formData.height" placeholder="请输入高" />
      </el-form-item>
      <el-form-item label="密度" prop="density">
        <el-input v-model="formData.density" placeholder="请输入密度" />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>
<script setup lang="ts">
import { ProductApi, ProductVO } from '@/api/erp/foundation/product'
import { warehouseAreaApi } from '@/api/erp/foundation/warehouseArea'
import { warehouseAreasApi } from '@/api/erp/foundation/warehouseAreas'
import { productUnitApi } from '@/api/erp/foundation/productUnit'
import { ProductCategoryApi, ProductCategoryVO } from '@/api/erp/product/category'
import { StockApi, DictItemConfigVO } from '@/api/erp/stock/stock'
const warehouseArea = ref<any[]>([])
/** ERP 产品 表单 */
defineOptions({ name: 'ProductForm' })

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗
const warehouseLocation = ref<any[]>([])

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const formData = ref({
  id: undefined,
  name: undefined,
  barCode: undefined,
  categoryId: undefined,
  unitId: undefined,
  status: undefined,
  standard: undefined,
  remark: undefined,
  expiryDay: undefined,
  weight: undefined,
  purchasePrice: undefined,
  salePrice: undefined,
  minPrice: undefined,
  unit: undefined,
  warehousingRemark: undefined,
  secondaryUnit: undefined,
  secondaryUnitQuantity: undefined,
  salePriceSecondary: undefined,
  costPriceSecondary: undefined,
  batchNumber: undefined,
  supplierName: undefined,
  spec: undefined,
  outerBoxSize: undefined,
  customerName: undefined,
  itemNo: undefined,
  packageInfo: undefined,
  cuttingCostPerMeter: undefined,
  piercingCostPerPiece: undefined,
  dottingCostPerPiece: undefined,
  weightNew: undefined,
  size: undefined,
  singleWeight: undefined,
  length: undefined,
  width: undefined,
  height: undefined,
  density: undefined,
  contractNumber: undefined,
  warehouse:undefined
})
const formRules = reactive({
  name: [{ required: true, message: '产品名称不能为空', trigger: 'blur' }],
  barCode: [{ required: true, message: '产品条码不能为空', trigger: 'blur' }],
  categoryId: [{ required: true, message: '产品分类编号不能为空', trigger: 'blur' }],
  unitId: [{ required: true, message: '单位编号不能为空', trigger: 'blur' }],
  status: [{ required: true, message: '产品状态不能为空', trigger: 'blur' }],
})
const warehouse= ref()
const formRef = ref() // 表单 Ref
const productCategory = ref()
const unitOption = ref()
const statusOptions = ref<{ value: string; label: string }[]>([])
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  itemType:1
})


/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type) + "产品"
  formType.value = type
  resetForm()
      const data = {
    dictCode: 'status'
  }
  unitOption.value = (await productUnitApi.pageList(queryParams)).list
  const response = await StockApi.getByDictCode(data)
  statusOptions.value = response.map((item) => ({
    value: item.value,
    label: item.description
  }))
  productCategory.value = await ProductCategoryApi.getProductCategoryList()

  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      formData.value = await ProductApi.getProduct(id)
    } finally {
      formLoading.value = false
    }
  }
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  await formRef.value.validate()
  // 提交请求
  formLoading.value = true
  try {
    const data = {
      ...formData.value,
      status: parseInt(formData.value.status as any),

    } as unknown as ProductVO

    if (formType.value === 'create') {
      await ProductApi.createProduct(data)
      message.success(t('common.createSuccess'))
    } else {
      await ProductApi.updateProduct(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    name: undefined,
    barCode: undefined,
    categoryId: undefined,
    unitId: undefined,
    status: undefined,
    standard: undefined,
    remark: undefined,
    expiryDay: undefined,
    weight: undefined,
    purchasePrice: undefined,
    salePrice: undefined,
    minPrice: undefined,
    warehouseLocationId: undefined,
    warehouseAreaId: undefined,
    productAttribute: undefined,
    unit: undefined,
    warehousingRemark: undefined,
    secondaryUnit: undefined,
    secondaryUnitQuantity: undefined,
    salePriceSecondary: undefined,
    costPriceSecondary: undefined,
    batchNumber: undefined,
    supplierName: undefined,
    spec: undefined,
    outerBoxSize: undefined,
    customerName: undefined,
    itemNo: undefined,
    packageInfo: undefined,
    cuttingCostPerMeter: undefined,
    piercingCostPerPiece: undefined,
    dottingCostPerPiece: undefined,
    weightNew: undefined,
    size: undefined,
    singleWeight: undefined,
    length: undefined,
    width: undefined,
    height: undefined,
    density: undefined,
    contractNumber: undefined
  }
  formRef.value?.resetFields()
}
</script>